package com.example.my.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.my.entity.Permission;
import com.example.my.entity.Role;
import com.example.my.entity.RolePermission;
import com.example.my.mapper.RoleMapper;
import com.example.my.mapper.RolePermissionMapper;
import com.example.my.service.PermissionService;
import com.example.my.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionService permissionService;

    @Override
    public void assignPermissions(Long roleId, List<Long> pIds) {
        // 1. 清空角色原有权限
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));


            if (pIds != null && !pIds.isEmpty()) {
                List<RolePermission> rps = pIds.stream()
                        .map(pId -> {
                            RolePermission rp = new RolePermission();
                            rp.setRoleId(roleId);
                            rp.setPermissionId(pId);
                            return rp;
                        })
                        .collect(Collectors.toList());

              for (RolePermission rp : rps)
                rolePermissionMapper.insert(rp);
            }
        }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return roleMapper.getRolesByUserId(userId);
    }

    @Override
    public Role getPermissionsByRoleId(Long roleId) {
        Role role = this.getById(roleId);
        List<Permission> permissions = permissionService.getPermissionsByRoleId(roleId);
        role.setPermissions(permissions);

        return null;
    }
}